import React, { useEffect, useState } from 'react';
import { Button, Form, Input, Select, Modal, Radio, DatePicker, message, Empty } from 'antd';
import { useStore } from '../stores/index';
import './StudentInfo.less';
import dayjs from 'dayjs';
import { myAxios } from '../axios';

const StudentInfo = ({ fetchStudentInfo }) => {
    const [form] = Form.useForm();
    const [isModalVisible, setIsModalVisible] = useState(false);
    const [isAddModalVisible, setIsAddModalVisible] = useState(false);
    const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
    const store = useStore();
    const [studentsArray, setStudentsArray] = useState([]);
    const [selectedStudent, setSelectedStudent] = useState(null);
    const [isManuallySelected, setIsManuallySelected] = useState(false);

    // 组件挂载时执行一次数据获取
    useEffect(() => {
        const init = async () => {
            setSelectedStudent(null);
            await fetchStudentInfo();
            const students = store.students;
            console.log('s', students);
            const newStudentsArray = Object.values(students);
            setStudentsArray(newStudentsArray);
        };
        init();
    }, [fetchStudentInfo]);

    useEffect(() => {
        if (!isManuallySelected && studentsArray.length > 0) {
            setSelectedStudent(studentsArray[0]);
            store.saveSelectStudent(studentsArray[0]);
        }
    }, [studentsArray, isManuallySelected]);

    // 处理选择学生的事件
    const handleSelectStudent = (studentId) => {
        const student = studentsArray.find(student => student.studentId === studentId);
        setSelectedStudent(student);
        setIsManuallySelected(true); // 标记为手动选择
        store.saveSelectStudent(student);
    };

    // 处理修改信息按钮点击事件
    const handleEditClick = () => {
        if (selectedStudent) {
            const formattedBirthdate = selectedStudent.birthdate ? dayjs(selectedStudent.birthdate) : null;
            form.setFieldsValue({
                ...selectedStudent,
                birthdate: formattedBirthdate
            });
            setIsModalVisible(true);
        }
    };

    // 处理新增学生按钮点击事件
    const handleAddStudent = () => {
        form.resetFields(); // 清空表单信息
        setIsAddModalVisible(true); // 显示新增学生弹窗
    };

    // 处理保存表单信息
    const handleSave = async (isAdd = false) => {
        try {
            const formValues = await form.validateFields();

            if (isAdd) {
                // 检查姓名重复性
                const isDuplicate = studentsArray.some(student => student.fullName === formValues.fullName);
                if (isDuplicate) {
                    message.error('该姓名已存在，请重新输入');
                    return;
                }
            }

            // 对gender进行转换
            let genderValue = formValues.gender;
            if (genderValue === '男') {
                genderValue = 'Male';
            } else if (genderValue === '女') {
                genderValue = 'Female';
            }
            console.log('保存的性别:', genderValue);

            let studentInfo = {
                fullName: formValues.fullName,
                gender: genderValue,
                birthdate: formValues.birthdate ? formValues.birthdate.format('YYYY-MM-DD') : null,
                grade: formValues.grade,
                school: formValues.school,
            };
            console.log('保存的学生信息:', studentInfo);
            let response;
            if (isAdd) {
                response = await myAxios.post('/stu/add', studentInfo);
                // 获取后端返回的 studentId 并添加到 studentInfo 中
                studentInfo.studentId = response.data.data;
                // 将新添加的学生信息添加到 studentsArray 中
                setStudentsArray([...studentsArray, studentInfo]);


                await fetchStudentInfo();
                // 更新 selectedStudent 状态为新添加的学生
                setSelectedStudent(studentInfo);
                setIsManuallySelected(true);
            } else {
                const studentId = store.selectStudent.studentId;
                studentInfo.studentId = studentId;
                response = await myAxios.put('/stu/update', studentInfo);
                // 直接使用 formValues.gender 来更新学生信息
                const updatedStudentInfo = {
                    ...studentInfo,
                    gender: formValues.gender
                };
                // 更新 studentsArray
                setStudentsArray(prevArray =>
                    prevArray.map(student =>
                        student.studentId === studentId ? updatedStudentInfo : student
                    )
                );
                setSelectedStudent(updatedStudentInfo);
                await fetchStudentInfo();
                // 手动更新 selectedStudent 的状态
                setSelectedStudent({
                    ...selectedStudent,
                    ...updatedStudentInfo
                });
            }
            console.log('结果:', response.data);


            setTimeout(() => {
                message.success('保存成功');
                if (isAdd) {
                    setIsAddModalVisible(false);
                } else {
                    setIsModalVisible(false);
                }
            }, 100);
        } catch (error) {
            console.log('Validation failed:', error);
        }
    };

    const handleDeleteClick = () => {
        if (selectedStudent) {
            setIsDeleteModalVisible(true);
        }
    };

    // 删除学生
    const handleConfirmDelete = async () => {
        if (selectedStudent) {
            Modal.confirm({
                title: '确认删除',
                content: `你确定要删除 ${selectedStudent.fullName} 的信息吗？`,
                okText: '确认',
                cancelText: '取消',
                onOk: async () => {
                    try {
                        console.log('删除的学生信息:', selectedStudent.studentId);
                        const response = await myAxios.delete(`/stu/delete/${selectedStudent.studentId}`);
                        console.log('删除结果:', response.data);
                        if (response.data && response.data.code === 200) {
                            await fetchStudentInfo();
                            const newStudentsArray = Object.values(store.students);
                            setStudentsArray(newStudentsArray);
                            if (newStudentsArray.length > 0) {
                                setSelectedStudent(newStudentsArray[0]);
                                store.saveSelectStudent(newStudentsArray[0]);
                            } else {
                                setSelectedStudent(null);
                                store.saveSelectStudent(null);
                            }
                            setIsDeleteModalVisible(false);
                            message.success('删除成功');
                        } else {
                            message.error('删除失败，请稍后重试');
                        }
                    } catch (error) {
                        console.log('删除学生信息时出错:', error);
                        message.error('删除失败，请稍后重试');
                    }
                },
                onCancel: () => {
                    // 用户点击取消，不做任何操作
                },
            });
        }
    };

    return (
        <>
            <div className='student-container'>
                <Button color="green" variant="solid" className='btn' onClick={handleAddStudent}>
                    新增学生
                </Button>

                <div className='if-students'>
                    <div className='btn-container'>
                        {studentsArray.length > 0 && (<Button color="green" variant="solid" className='btn' onClick={handleEditClick}>
                            修改信息
                        </Button>)}
                        {studentsArray.length > 0 && (<Button color="red" variant="solid" className='btn' onClick={handleDeleteClick}>
                            删除信息
                        </Button>)}
                    </div>
                    <Select
                        className="student-select"
                        placeholder="未存在学生"
                        value={selectedStudent?.fullName}
                        onChange={handleSelectStudent}
                    >
                        {studentsArray.map(student => (
                            <Select.Option key={student.studentId} value={student.studentId}>
                                {student.fullName}
                            </Select.Option>
                        ))}
                    </Select>
                </div>

            </div>
            {studentsArray.length > 0 && selectedStudent ? (
                <ul className="students-info">
                    <li>
                        <label>学生姓名</label>:
                        <span>{selectedStudent.fullName}</span>
                    </li>
                    <li>
                        <label>性别</label>:
                        <span>{selectedStudent.gender}</span>
                    </li>
                    <li>
                        <label>生日</label>:
                        <span>{selectedStudent.birthdate}</span>
                    </li>
                    <li>
                        <label>年级</label>:
                        <span>{selectedStudent.grade}</span>
                    </li>
                    <li>
                        <label>学校</label>:
                        <span>{selectedStudent.school}</span>
                    </li>
                </ul>
            ) : (<Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />)}
            {/* 修改信息弹窗 */}
            <Modal
                className='modal-edit'
                title="修改学生信息"
                open={isModalVisible}
                onCancel={() => setIsModalVisible(false)}
                footer={[
                    <Button key="back" onClick={() => setIsModalVisible(false)}>
                        返回
                    </Button>,
                    <Button key="save" type="primary" onClick={() => handleSave(false)}>
                        保存
                    </Button>,
                ]}
            >
                <Form form={form} layout="vertical" style={{ margin: '40px' }}>
                    <Form.Item
                        name="fullName"
                        label="学生姓名"
                        rules={[
                            { required: true, message: '请输入学生姓名' },
                            { pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名必须为中文' }
                        ]}
                    >
                        <Input style={{ width: 150 }} />
                    </Form.Item>
                    <Form.Item
                        name="gender"
                        label="性别"
                        rules={[{ required: true, message: '请选择性别' }]}
                    >
                        <Radio.Group>
                            {genderOptions.map(option => (
                                <Radio key={option.value} value={option.value}>
                                    {option.label}
                                </Radio>
                            ))}
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        name="birthdate"
                        label="生日"
                        rules={[{ required: true, message: '请选择生日' }]}
                    >
                        <DatePicker format="YYYY-MM-DD" />
                    </Form.Item>
                    <Form.Item
                        name="grade"
                        label="年级"
                        rules={[{ required: true, message: '请选择年级' }]}
                    >
                        <Select placeholder="请选择年级" style={{ width: 150 }} >
                            {gradeOptions.map(option => (
                                <Select.Option key={option.value} value={option.value}>
                                    {option.label}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="school"
                        label="学校"
                        rules={[{ required: true, message: '请输入学校名称' }]}
                    >
                        <Input style={{ width: 400 }} />
                    </Form.Item>
                </Form>
            </Modal>
            {/* 新增学生弹窗 */}
            <Modal
                className='modal-edit'
                title="新增学生信息"
                open={isAddModalVisible}
                onCancel={() => setIsAddModalVisible(false)}
                footer={[
                    <Button key="back" onClick={() => setIsAddModalVisible(false)}>
                        返回
                    </Button>,
                    <Button key="save" type="primary" onClick={() => handleSave(true)}>
                        保存
                    </Button>,
                ]}
            >
                <Form form={form} layout="vertical" style={{ margin: '40px' }}>
                    <Form.Item
                        name="fullName"
                        label="学生姓名"
                        rules={[
                            { required: true, message: '请输入学生姓名' },
                            { pattern: /^[\u4e00-\u9fa5]+$/, message: '姓名必须为中文' }
                        ]}
                    >
                        <Input style={{ width: 150 }} />
                    </Form.Item>
                    <Form.Item
                        name="gender"
                        label="性别"
                        rules={[{ required: true, message: '请选择性别' }]}
                    >
                        <Radio.Group>
                            {genderOptions.map(option => (
                                <Radio key={option.value} value={option.value}>
                                    {option.label}
                                </Radio>
                            ))}
                        </Radio.Group>
                    </Form.Item>
                    <Form.Item
                        name="birthdate"
                        label="生日"
                        rules={[{ required: true, message: '请选择生日' }]}
                    >
                        <DatePicker format="YYYY-MM-DD" />
                    </Form.Item>
                    <Form.Item
                        name="grade"
                        label="年级"
                        rules={[{ required: true, message: '请选择年级' }]}
                    >
                        <Select placeholder="请选择年级" style={{ width: 150 }} >
                            {gradeOptions.map(option => (
                                <Select.Option key={option.value} value={option.value}>
                                    {option.label}
                                </Select.Option>
                            ))}
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="school"
                        label="学校"
                        rules={[{ required: true, message: '请输入学校名称' }]}
                    >
                        <Input style={{ width: 400 }} />
                    </Form.Item>
                </Form>
            </Modal>
            {/* 删除信息弹窗 */}
            <Modal
                className='modal-edit'
                title="删除学生信息"
                open={isDeleteModalVisible}
                onCancel={() => setIsDeleteModalVisible(false)}
                footer={[
                    <Button key="back" onClick={() => setIsDeleteModalVisible(false)}>
                        返回
                    </Button>,
                    <Button key="delete" type="primary" danger onClick={handleConfirmDelete}>
                        确认删除
                    </Button>,
                ]}
            >
                {selectedStudent ? <div className="delete-info">
                    <div>
                        <label>学生姓名</label>:
                        <span>{selectedStudent.fullName}</span>
                    </div>
                    <div>
                        <label>性别</label>:
                        <span>{selectedStudent.gender}</span>
                    </div>
                    <div>
                        <label>生日</label>:
                        <span>{selectedStudent.birthdate}</span>
                    </div>
                    <div>
                        <label>年级</label>:
                        <span>{selectedStudent.grade}</span>
                    </div>
                    <div>
                        <label>学校</label>:
                        <span>{selectedStudent.school}</span>
                    </div>
                </div> : null}
            </Modal>
        </>
    );
};

const chineseNumbers = ['一', '二', '三', '四', '五', '六'];
const gradeOptions = [];
// 表单-年级选择
// 小学
for (let i = 0; i < 6; i++) {
    gradeOptions.push({
        label: `小学${chineseNumbers[i]}年级`,
        value: `小学${chineseNumbers[i]}年级`
    });
}
// 初中
for (let i = 0; i < 3; i++) {
    gradeOptions.push({
        label: `初中${chineseNumbers[i]}年级`,
        value: `初中${chineseNumbers[i]}年级`
    });
}
// 高中
for (let i = 0; i < 3; i++) {
    gradeOptions.push({
        label: `高中${chineseNumbers[i]}年级`,
        value: `高中${chineseNumbers[i]}年级`
    });
}
// 大学
for (let i = 0; i < 4; i++) {
    gradeOptions.push({
        label: `大学${chineseNumbers[i]}年级`,
        value: `大学${chineseNumbers[i]}年级`
    });
}
// 表单-性别选择
const genderOptions = [
    { label: '男', value: '男' },
    { label: '女', value: '女' }
];

export default StudentInfo;